from docx import Document
from docx.shared import Pt, Cm, RGBColor
from docx.oxml.ns import qn
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import re

def create_word_document(file_paths, output_path):
    # 创建文档
    doc = Document()
    
    # 设置页边距（1cm）
    sections = doc.sections
    for section in sections:
        section.top_margin = Cm(1)
        section.bottom_margin = Cm(1)
        section.left_margin = Cm(1)
        section.right_margin = Cm(1)
    
    # 设置默认字体（汉仪润圆-75W，四号）
    doc.styles['Normal'].font.name = '汉仪润圆-75W'
    doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), '汉仪润圆-75W')
    doc.styles['Normal'].font.size = Pt(14)  # 四号字
    
    # 设置默认行距（固定值16磅），段前段后0磅
    doc.styles['Normal'].paragraph_format.line_spacing = Pt(16)
    doc.styles['Normal'].paragraph_format.space_before = Pt(0)
    doc.styles['Normal'].paragraph_format.space_after = Pt(0)
    
    for file_path in file_paths:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 处理文件内容
        process_content(doc, content)
        
        # 添加分页符
        doc.add_page_break()
    
    # 保存文档
    doc.save(output_path)

def process_content(doc, content):
    # 处理任务信息
    task_matches = re.findall(r'\{\{任务\|(.*?)\|已完善=是\}\}', content, re.DOTALL)
    for task in task_matches:
        format_task_info(doc, task)
    
    # 处理折叠内容
    content = re.sub(r'\{\{折叠\|.*?\|内容=(.*?)\}\}', r'\1', content, flags=re.DOTALL)
    content = re.sub(r'\{\{折叠\|.*?title=(.*?)\|.*?content=(.*?)\}\}', r'\1\n\2', content, flags=re.DOTALL)
    
    # 处理注音 - 先替换为特殊标记
    content = re.sub(r'\{\{注音\|(.*?)\|(.*?)\}\}', r'【\1|\2】', content)
    
    # 处理颜色标记
    content = re.sub(r'\{\{颜色\|.*?\|(\{\{.*?\}\})?(.*?)\}\}', r'\2', content, flags=re.DOTALL)
    
    # 处理其他标记
    content = re.sub(r'\{\{.*?\}\}', '', content)
    content = re.sub(r'\[\[.*?\]\]', '', content)
    content = re.sub(r'<br>', '\n', content)
    content = re.sub(r'----', '-'*30, content)
    
    # 按行处理内容
    lines = content.split('\n')
    for line in lines:
        line = line.strip()
        if not line:
            continue
        
        # 处理标题
        if line.startswith('==') and line.endswith('=='):
            title = line.strip('=')
            add_heading(doc, title, level=1)
        elif line.startswith('===') and line.endswith('==='):
            title = line.strip('=')
            add_heading(doc, title, level=2)
        elif line.startswith('====') and line.endswith('===='):
            title = line.strip('=')
            add_heading(doc, title, level=3)
        else:
            # 处理普通文本，删除对话前的星号
            line = re.sub(r'^\*\s*', '', line)
            if line:
                add_paragraph(doc, line)

def format_task_info(doc, task_content):
    # 提取任务信息
    task_info = {}
    for match in re.finditer(r'\|(.*?)=(.*?)(?=\||$)', task_content, re.DOTALL):
        key = match.group(1).strip()
        value = match.group(2).strip()
        task_info[key] = value
    
    # 格式化任务信息
    if '任务名称' in task_info:
        add_heading(doc, task_info['任务名称'], level=2)
    
    if '任务地区' in task_info:
        add_formatted_line(doc, f"任务地区：{task_info['任务地区']}")
    
    if '任务描述' in task_info:
        # 处理任务描述中的换行
        desc = task_info['任务描述'].replace('<br>', '\n')
        add_formatted_line(doc, f"任务描述：{desc}")
    
    if '出场人物' in task_info:
        add_formatted_line(doc, f"出场人物：{task_info['出场人物']}")
    
    if '系列任务' in task_info:
        add_formatted_line(doc, f"系列任务：{task_info['系列任务']}")
    
    if '任务流程' in task_info:
        add_formatted_line(doc, "任务流程：")
        # 处理任务流程
        steps = re.findall(r'\*\s*(.*?)(?=\*\s*|$)', task_info['任务流程'])
        for i, step in enumerate(steps, 1):
            add_formatted_line(doc, f"{i}.{step.strip()}")

def add_formatted_line(doc, text):
    p = doc.add_paragraph()
    p.paragraph_format.line_spacing = Pt(16)
    p.paragraph_format.space_before = Pt(0)
    p.paragraph_format.space_after = Pt(0)
    run = p.add_run(text)
    run.font.name = '汉仪润圆-75W'
    run._element.rPr.rFonts.set(qn('w:eastAsia'), '汉仪润圆-75W')
    run.font.size = Pt(14)

def add_heading(doc, text, level):
    heading = doc.add_heading(level=level)
    run = heading.add_run(text)
    run.font.name = '汉仪润圆-75W'
    run._element.rPr.rFonts.set(qn('w:eastAsia'), '汉仪润圆-75W')
    run.font.size = Pt(14)
    heading.paragraph_format.line_spacing = Pt(16)
    heading.paragraph_format.space_before = Pt(0)
    heading.paragraph_format.space_after = Pt(0)

def add_paragraph(doc, text):
    # 检查是否有需要特殊处理的内容（如注音）
    if '【' in text and '】' in text:
        # 处理有注音的行，增加行距
        p = doc.add_paragraph()
        p.paragraph_format.line_spacing = Pt(20)  # 注音行增加行距
        p.paragraph_format.space_before = Pt(0)
        p.paragraph_format.space_after = Pt(0)
        
        # 分割文本和注音
        parts = re.split(r'(【.*?】)', text)
        
        for part in parts:
            if part.startswith('【') and part.endswith('】'):
                # 处理注音部分
                base_ruby = part.strip('【】').split('|')
                if len(base_ruby) == 2:
                    base, ruby = base_ruby
                    # 先添加基础文本
                    run = p.add_run(base)
                    run.font.name = '汉仪润圆-75W'
                    run._element.rPr.rFonts.set(qn('w:eastAsia'), '汉仪润圆-75W')
                    run.font.size = Pt(14)
                    
                    # 添加注音（上标）
                    run = p.add_run(ruby)
                    run.font.name = '汉仪润圆-75W'
                    run._element.rPr.rFonts.set(qn('w:eastAsia'), '汉仪润圆-75W')
                    run.font.size = Pt(10)  # 注音字体小一些
                    run.font.superscript = True
            else:
                # 普通文本
                run = p.add_run(part)
                run.font.name = '汉仪润圆-75W'
                run._element.rPr.rFonts.set(qn('w:eastAsia'), '汉仪润圆-75W')
                run.font.size = Pt(14)
    else:
        # 普通段落
        p = doc.add_paragraph(text)
        p.paragraph_format.line_spacing = Pt(16)
        p.paragraph_format.space_before = Pt(0)
        p.paragraph_format.space_after = Pt(0)
        for run in p.runs:
            run.font.name = '汉仪润圆-75W'
            run._element.rPr.rFonts.set(qn('w:eastAsia'), '汉仪润圆-75W')
            run.font.size = Pt(14)

# 使用示例
if __name__ == "__main__":
    input_files = ['1今天是昨天的明天\\1混乱行至深处.txt', '1今天是昨天的明天\\2漩涡止于中心.txt']  # 替换为实际文件路径
    output_file = '星穹铁道任务文档.docx'
    create_word_document(input_files, output_file)